package com.qingcloud.df.executor.process;

import com.qingcloud.df.executor.pojo.process.config.AllowedHosts;
import com.qingcloud.df.executor.pojo.process.config.ResourceRequirements;
import com.qingcloud.df.sdk.component.context.CompInstContext;
import org.apache.commons.lang3.RandomStringUtils;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public interface ProcessFactory {
    String VERSION_DELIMITER = ":";
    String DOCKER_DELIMITER = "/";
    Pattern ALPHABETIC = Pattern.compile("[a-zA-Z]+");

    public static final int DOCKER_NAME_LEN_LIMIT = 128;


    default  Process bulidProcess(String imageName,
                                  String suffix,
                                  String rootPath,
                                  String componentNameEn,
                                  String... jarCommand) throws Exception {

        return bulidProcess(imageName,suffix,rootPath,componentNameEn,null,null,null,null,jarCommand);
    }

    public Process bulidProcess(String imageName,
                                String suffix,
                                String rootPath,
                                String componentNameEn,
                                Map<String, String> files,
                                String entrypoint,
                                ResourceRequirements resourceRequirements,
                                AllowedHosts allowedHosts,
                                String... args) throws Exception;

    void processStop(String imageName ,String suffix);

    static String createProcessName(String fullImagePath, String suffix, int lenLimit) {
        var imageName = extractShortImageName(fullImagePath);
        var processName = imageName + "-" + suffix;
        if (processName.length() > lenLimit) {
            var extra = processName.length() - lenLimit;
            imageName = imageName.substring(extra);
            processName = imageName + "-" + suffix;
        }
        Matcher m = ALPHABETIC.matcher(processName);
        m.find();
        return processName.substring(m.start());
    }
    static String extractShortImageName(String fullImagePath) {
        var noVersion = fullImagePath.split(VERSION_DELIMITER)[0];
        var nameParts = noVersion.split(DOCKER_DELIMITER);
        return nameParts[nameParts.length - 1];
    }
}
